package com.imooc.article.controller;

import com.imooc.api.controller.article.ArticlePortalControllerApi;
import com.imooc.api.controller.user.BaseControllerApi;
import com.imooc.api.controller.user.UserControllerApi;
import com.imooc.article.service.ArticlePortalService;
import com.imooc.grance.result.GraceJsonResult;
import com.imooc.pojo.Article;
import com.imooc.pojo.vo.AppUserInfoVO;
import com.imooc.pojo.vo.ArticleDetaiVO;
import com.imooc.pojo.vo.IndexArticleVO;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.PagedGridResult;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/18/17:16
 * @Description:
 */
@RestController
public class ArticlePortalController extends BaseControllerApi implements ArticlePortalControllerApi {

    @Autowired
    private ArticlePortalService articlePortalService;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public GraceJsonResult articleList(@RequestParam Integer category,
                                       @RequestParam @ApiParam(value = "要查看的页数") Integer page,
                                       @RequestParam @ApiParam(value = "一页显示几条数据") Integer pageSize,
                                       @RequestParam String keyword) {
        if (page == null) {
            page = COMMON_PAGE;
        }
        if (pageSize == null) {
            pageSize = COMMON_PAGE_SIZE;
        }
        PagedGridResult pagedGridResult = articlePortalService.articleProtalList(keyword,
                                                                    page,
                                                                    pageSize,
                                                                    category);
        List<IndexArticleVO> indexArticleList = rebuildArticleGrid(pagedGridResult);

        pagedGridResult.setRows(indexArticleList);
        return GraceJsonResult.ok(pagedGridResult);
    }

    @Override
    public GraceJsonResult hotList() {
        List<Article> hotList = articlePortalService.getHotList();
        return GraceJsonResult.ok(hotList);
    }

    /**
     * 获得 AppUserInfoVO ，用于拼接list
     * @param userId
     * @param list
     * @return
     */
    /**
     * 从publisherList中获得匹配的用户
     * @param publisherId
     * @param publisherList
     * @return
     */
    private AppUserInfoVO getUserIfEqualPublisher(String publisherId,
                                              List<AppUserInfoVO> publisherList) {
        for (AppUserInfoVO u : publisherList) {
            if (u.getId().equalsIgnoreCase(publisherId)) {
                return u;
            }
        }
        return null;
    }

    @Override
    public GraceJsonResult queryArticleListOfWriter(Integer page, Integer pageSize, String writerId) {
        if (page == null) {
            page = COMMON_PAGE;
        }
        if (pageSize == null) {
            pageSize = COMMON_PAGE_SIZE;
        }
        PagedGridResult pagedGridResult =
                                        articlePortalService.writerArticleList(writerId,
                                        page,
                                        pageSize);
        List<IndexArticleVO> indexArticleList = rebuildArticleGrid(pagedGridResult);

        pagedGridResult.setRows(indexArticleList);
        return GraceJsonResult.ok(pagedGridResult);
    }

    @Override
    public GraceJsonResult hotList(String writerId) {
        PagedGridResult gridResult = articlePortalService.writerHotArticleList(writerId);
        return GraceJsonResult.ok(gridResult);
    }

    @Override
    public GraceJsonResult detail(String articleId) {
        ArticleDetaiVO articleDetaiVO = articlePortalService.getArticleDetaiVO(articleId);
        //远程调用获取作者的昵称
        Set idSet = new HashSet();
        idSet.add(articleDetaiVO.getPublishUserId());
        List<AppUserInfoVO> userInfoVOList = getUSerInfoVOList(idSet);
        if (!userInfoVOList.isEmpty()) {
            articleDetaiVO.setPublishUserName(userInfoVOList.get(0).getNickname());
        }
        articleDetaiVO.setReadCounts(getCountsFromRedis(REDIS_ARTICLE_READ_COUNTS+":"+articleId));
        return GraceJsonResult.ok(articleDetaiVO);
    }

    @Override
    public GraceJsonResult readArticle(String articleId, HttpServletRequest request) {
        articlePortalService.readArticle(articleId,request);
        return GraceJsonResult.ok();
    }

    @Override
    public Integer readCounts(String articleId) {
        String counts = redis.get(REDIS_ARTICLE_READ_COUNTS + ":" + articleId);
        Integer readCounts = Integer.valueOf(counts);
        return readCounts;
    }

    private List<IndexArticleVO> rebuildArticleGrid(PagedGridResult pageResult) {

        List<Article> list = (List<Article>) pageResult.getRows();
        Set<String> idSet = new HashSet<>();

        List<String> articleIdList = new ArrayList<>();
        for (Article article : list) {
            //1.构建发布者id列表
            idSet.add(article.getPublishUserId());
            //构建文章id的list
            articleIdList.add(REDIS_ARTICLE_READ_COUNTS + ":" + article.getId());
        }
        //使用mget方式请求，一次性获取所有的文章阅读数，减少损耗
        List<String> readCountsRedis = redis.mget(articleIdList);
        //2.发起远程调用(RestTemplate)，请求用户服务获得用户(文章发布者)列表
        List<AppUserInfoVO> userInfoVOList = getUSerInfoVOList(idSet);
        //检测
        /*for (AppUserInfoVO appUserInfoVO : userInfoVOList) {
            System.out.println("userInfoVO.userId: "+appUserInfoVO.getId());
        }*/

        //3.拼接两个list，重组文章列表

        List<IndexArticleVO> indexArticleList = new ArrayList<>();
        //遍历所有文章列表
        /*for (Article a : list) {
            IndexArticleVO indexArticleVO = new IndexArticleVO();
            BeanUtils.copyProperties(a, indexArticleVO);

            // 3.1 从userList中获得publisher基本信息
            AppUserInfoVO publisher = getUserIfEqualPublisher(a.getPublishUserId(), userInfoVOList);

            // 3.2从redis中获取阅读数
            String readCounts = getCountsFromRedis(REDIS_ARTICLE_READ_COUNTS + ":" + a.getId());
            if (StringUtils.isBlank(readCounts)) {
                readCounts = "0";
            }
            indexArticleVO.setReadCounts(Integer.valueOf(readCounts));
            // 3.3 把文章放入新的文章list中
            indexArticleVO.setPublisherVO(publisher);
            indexArticleList.add(indexArticleVO);
        }*/

        for (int i =0;i<list.size();i++) {
            IndexArticleVO indexArticleVO = new IndexArticleVO();
            Article a = list.get(i);
            BeanUtils.copyProperties(a, indexArticleVO);

            // 3.1 从userList中获得publisher基本信息
            AppUserInfoVO publisher = getUserIfEqualPublisher(a.getPublishUserId(), userInfoVOList);

            // 3.2从redis中获取阅读数
            String readCounts = readCountsRedis.get(i);
            if (StringUtils.isBlank(readCounts)) {
                readCounts = "0";
            }
            indexArticleVO.setReadCounts(Integer.valueOf(readCounts));
            // 3.3 把文章放入新的文章list中
            indexArticleVO.setPublisherVO(publisher);
            indexArticleList.add(indexArticleVO);
        }
        return indexArticleList;
    }

    /**
     * rest远程调用，根据用户id获取用户的基本信息
     *
     * @param idSet
     * @return
     */

    @Autowired
    private UserControllerApi userController;

    public List<AppUserInfoVO> getUSerInfoVOList(Set idSet) {
        //使用feign发起调用，直接调用接口,解决硬编码拼接调用的弊端
        GraceJsonResult body = userController.queryByIds(JsonUtils.objectToJson(idSet));
//        System.out.println("body: "+body);
        //使用微服务的注册与发现远程调用方法
//        String serviceId = "SERVICE-USER";
//        //直接调用serviceId,他会自动的去注册表中为我们去寻找对应的ip和端口号,另外还要在RestTemplate上添加负载均衡的注解
//        String url =
//                "http://"+serviceId+"/user/queryByIds?userIds=" + JsonUtils.objectToJson(idSet);
        /*List<ServiceInstance> instanceList = discoveryClient.getInstances(serviceId);
        ServiceInstance userServiceInstance = instanceList.get(0);
        String host = userServiceInstance.getHost();
        int port = userServiceInstance.getPort();
        String url =
                "http://"+host+":"+port+"/user/queryByIds?userIds=" + JsonUtils.objectToJson(idSet);
*/

//        String url =
//                "http://user.imoocnews.com:8003/user/queryByIds?userIds=" + JsonUtils.objectToJson(idSet);
//        ResponseEntity<GraceJsonResult> entityResult =
//                restTemplate.getForEntity(url, GraceJsonResult.class);
//        GraceJsonResult body = entityResult.getBody();
        List<AppUserInfoVO> userInfoVOList = null;

        if (body.getStatus() == 200) {
            String userListJson = JsonUtils.objectToJson(body.getData());
            userInfoVOList = JsonUtils.jsonToList(userListJson, AppUserInfoVO.class);
//            System.out.println("userInfoVOList: "+userInfoVOList.toString());
        }else {
            userInfoVOList = new ArrayList<>();
        }
        return userInfoVOList;
    }


}
